import hashlib

from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .models import User
from note.views import check_login
from note.models import Note


# Create your views here.
def reg_view(request):
    if request.method == 'GET':
        return render(request, 'user/register.html')
    elif request.method == 'POST':
        res = {}
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_exists = True if User.objects.filter(username=username) else False
        if user_exists:
            res['code'] = 500
            res['msg'] = "请更换用户名重试"
        else:
            # 防止并发写入
            try:
                # md5算法对密码进行加密
                m = hashlib.md5()
                m.update(password.encode())
                password_md5 = m.hexdigest()
                user = User.objects.create(username=username, password=password_md5)
                res['code'] = 200
                res['msg'] = "注册成功"
                request.session['username'] = username
                request.session['uid'] = user.id
            except Exception as e:
                print(f'--create user error {e}')
                res['code'] = 500
                res['msg'] = "请更换用户名重试"

        return JsonResponse(res)
    else:
        return render(request, '404.html')


def login_view(request):
    if request.method == 'GET':
        # 先检查session
        if request.session.get('username') and request.session.get('uid'):
            return redirect('/index')
        # 再检查cookie
        cookie_username = request.COOKIES.get('username')
        cookie_uid = request.COOKIES.get('uid')
        if cookie_uid and cookie_username:
            # 回写session
            request.session['username'] = cookie_username
            request.session['uid'] = cookie_uid
        return render(request, 'user/login.html')
    elif request.method == 'POST':
        res = {}
        username = request.POST.get('username')
        password = request.POST.get('password')
        remember = request.POST.get('remember')
        m = hashlib.md5()
        m.update(password.encode())
        password_md5 = m.hexdigest()
        try:
            user = User.objects.get(username=username, password=password_md5)
            res['code'] = 200
            res['msg'] = "登录成功"
            request.session['username'] = username
            request.session['uid'] = user.id
            if remember == 'true':
                response = JsonResponse(res)
                response.set_cookie('username', username, 3*24*60*60)
                response.set_cookie('uid', user.id, 3*24*60*60)
                return response

        except Exception as e:
            print(f'--login user error {e}')
            res['code'] = 500
            res['msg'] = "用户名或密码错误"
        return JsonResponse(res)

    else:
        return render(request, '404.html')


def index_view(request):
    return render(request, 'index/index.html')

def logout_view(request):
    if 'username' in request.session:
        del request.session['username']
    if 'uid' in request.session:
        del request.session['uid']
    response = HttpResponseRedirect('/index')
    if 'username' in request.COOKIES:
        response.delete_cookie('username')
    if 'uid' in request.COOKIES:
        response.delete_cookie('uid')
    return response


@check_login
def notes_view(request):
    uid = request.session.get('uid')
    notes = Note.objects.filter(user_id=uid)
    data = {
        'count': len(notes),
        'notes': []
    }
    for i in range(len(notes)):
        data['notes'].append({
            'id': notes[i].id,
            'title': notes[i].title,
            'created_time': notes[i].created_time,
            'updated_time': notes[i].updated_time,

        })
    return render(request, 'note/list_notes.html', context=data)